<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>jquery上传图片</title>
        <link
            rel="stylesheet"
            href="https://static.web.sdo.com/chuanshi/common/style/bootstrap.min.css"
        />
        <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.3/axios.min.js"></script>
        <style>
            .wrapper {
                width: 100vw;
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: #eee;
            }
            .box {
                width: 500px;
                box-sizing: border-box;
                padding: 40px;
                background-color: #fff;
                box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="box">
                <div class="form-group">
                    <label for="name">姓名</label>
                    <input
                        type="text"
                        class="form-control"
                        id="name"
                        name="name"
                    />
                </div>
                <div class="form-group">
                    <label for="age">年龄</label>
                    <input
                        type="number"
                        class="form-control"
                        id="age"
                        name="age"
                    />
                </div>
                <div class="form-group">
                    <label for="file">选择文件</label>
                    <input
                        type="file"
                        class="form-control-file"
                        id="file"
                        name="avatar"
                    />
                </div>
                <button type="submit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </body>
</html>
<script>
    const submit = document.querySelector(".btn-primary");
    const file = document.querySelector(".form-control-file");
    submit.addEventListener("click", async (e) => {
        const data = new FormData();
        data.append("avatar", file.files[0]);
        const res = await axios.post("/api/upload", data, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        });
        if (res.data.code === 200) {
            console.log(res.data.data);
            alert("上传成功");
        }
    });
</script>
